package com.spring.security.authserver.service.impl;

import com.spring.security.authserver.bean.SysUser;
import com.spring.security.authserver.mapper.PermissionMapper;
import com.spring.security.authserver.mapper.UserMapper;
import com.spring.security.authserver.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser user = getByUsername(s);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();

        permissionMapper.selectByUserId(user.getId()).forEach(permission -> {
            if (permission != null && StringUtils.isNotEmpty(permission.getEnname())) {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getUrl());
                authorities.add(grantedAuthority);
            }
        });
        return new User(user.getUsername(), user.getPassword(), authorities);
    }

    @Override
    public SysUser getByUsername(String username) {
        return userMapper.getByUsername(username);
    }
}
